<template>
  <div class="table">
    <!-- <el-input
      placeholder="请输入指标名称"
      v-model="indicatorName"
      suffix-icon="el-icon-search"
      @input="filterTable"
    >
    </el-input> -->
    <div class="top">
      <el-input
        placeholder="请输入指标名称"
        v-model="page.name"
        suffix-icon="el-icon-search"
        @input="filterTable"
        class="top-item"
      >
      </el-input>
      <el-select
        v-model="page.areaId"
        placeholder="体检城市"
        clearable
        :loading="cityOptionsLoading"
        @change="handleCityChange"
        class="top-item-sel"
      >
        <el-option
          v-for="item in cityOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-select
        v-model="page.year"
        placeholder="体检年份"
        clearable
        :loading="yearOptionsLoading"
        @change="handleYearChange"
        class="top-item-sel"
      >
        <el-option
          v-for="item in yearOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-select
        v-model="page.dimensionId"
        placeholder="所属维度"
        clearable
        :loading="dimensionOptionsLoading"
        @change="handleDimensionChange"
        class="top-item-sel"
      >
        <el-option
          v-for="item in dimensionOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-input
        placeholder="请输入所属指标体系"
        v-model="page.quotaName"
        suffix-icon="el-icon-search"
        @input="filterIndex"
        class="top-item"
      >
      </el-input>
    </div>
    <el-table
      :data="tableData"
      header-row-class-name="cus-header-row"
      ref="tableRef"
      stripe
      width="100%"
      height="600"
      @selection-change="handleSelectionChange"
      @select="handleSelect"
    >
      <el-table-column type="selection" width="50"> </el-table-column>
      <!-- <el-table-column
        prop="name"
        label="指标名称"
        :filters="[{ text: '指标', value: '指标' }]"
        :filter-method="filterHandler"
      >
      </el-table-column> -->
      <el-table-column prop="name" label="指标名称"> </el-table-column>
      <el-table-column prop="areaName" label="体检城市" width="100">
      </el-table-column>
      <el-table-column prop="year" label="体检年份" width="80">
      </el-table-column>
      <el-table-column prop="introduction" label="指标释义">
        <template slot-scope="scope">
          <div class="index-definition" :title="scope.row.introduction">
            {{ scope.row.introduction }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="dimensionName" label="所属维度" width="100">
      </el-table-column>
      <el-table-column prop="quotaName" label="所属指标体系"> </el-table-column>
    </el-table>
    <div class="footer">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageIndex"
        :page-sizes="[10, 15, 20, 25]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getAreaList,
  getYearList,
  queryDimensionByIndex,
} from '@api/indicator-manage'
export default {
  props: {
    tableData: {
      required: true,
      type: Array,
      default: () => [],
    },
    defaultSelection: {
      type: Array,
      default: () => [],
    },
    selectIndicatorArr: {
      type: Array,
      default: () => [],
    },
    page: {
      type: Object,
      require: true,
    },
    // pageQuery: {
    //   type: Object,
    //   required: true,
    // },
    // loading: {
    //   type: Boolean,
    //   required: true,
    // },
  },
  data() {
    return {
      tableRef: null,
      selection: [],
      tempSelection: [],
      indicatorName: '',
      cityOptions: [],
      cityOptionsLoading: true,
      yearOptions: [],
      yearOptionsLoading: true,
      dimensionOptions: [
        {
          label: '1',
          value: '1',
        },
      ],
      dimensionOptionsLoading: true,
    }
  },
  watch: {
    tableData: {
      handler(newVal, oldVal) {
        if (newVal && newVal.length) {
          if (oldVal.length === 0) {
            this.$nextTick(() => {
              const idList = this.tempSelection.map((item) => item.pkid)
              this.tableData.forEach((item) => {
                if (idList.some((id) => id === item.pkid)) {
                  this.$refs.tableRef.toggleRowSelection(item)
                }
              })
            })
          } else {
            if (newVal[0].pkid !== oldVal[0].pkid) {
              this.$nextTick(() => {
                const idList = this.tempSelection.map((item) => item.pkid)
                this.tableData.forEach((item) => {
                  if (idList.some((id) => id === item.pkid)) {
                    this.$refs.tableRef.toggleRowSelection(item)
                  }
                })
              })
            }
          }
        }
      },
    },
    selectIndicatorArr: {
      handler(newValue) {
        //清空选择的指标
        this.$refs.tableRef.clearSelection()
        //默认选择该节点所关联指标
        this.handleSelectionChange(newValue)
        newValue.map((item) => {
          this.$refs.tableRef.toggleRowSelection(item)
        })
      },
      deep: true,
    },
    yearAndArea(val) {
      if (val) {
        const params = {
          year: this.page.year,
          areaId: this.page.areaId,
        }
        queryDimensionByIndex(params).then((res) => {
          if (res.success) {
            if (res.data) {
              this.dimensionOptions = res.data.map((item) => {
                return {
                  label: item.indexDimension.name,
                  value: item.indexDimension.pkid,
                }
              })
              this.dimensionOptionsLoading = false
              // this.page.dimensionId = this.dimensionOptions[0].label;
            }
            // this.treeLoading = false;
          }
        })
      }
    },
    defaultSelection(val) {
      this.tempSelection = val
    },
  },
  created() {
    this.fetchData(true)
  },
  computed: {
    yearAndArea() {
      return this.page.areaId && this.page.year
    },
  },
  mounted() {
    // 默认选中项
    // const idList = this.defaultSelection.map((item) => item.pkid);
    // this.tableData.forEach((item) => {
    //   if (idList.some((id) => id === item.pkid)) {
    //    this.$refs.tableRef.toggleRowSelection(item);
    //   }
    // });
    this.$nextTick(() => {
      this.tempSelection = this.defaultSelection
      const idList = this.tempSelection.map((item) => item.pkid)
      this.tableData.forEach((item) => {
        if (idList.some((id) => id === item.pkid)) {
          this.$refs.tableRef.toggleRowSelection(item)
        }
      })
    })
  },
  methods: {
    handleSelectionChange(selection) {
      // this.selection = JSON.parse(localStorage.getItem('indicaotrs'));
      // this.$refs.tableRef.toggleRowSelection(sel[0]);
      this.selection = selection
      // this.$emit("selection-change", selection);
      this.$emit('selection-change', this.tempSelection)
    },
    handleSelect(selection, row) {
      if (selection.find((item) => item.pkid === row.pkid)) {
        this.tempSelection.push(row)
      } else {
        const index = this.tempSelection.findIndex(
          (item) => item.pkid === row.pkid
        )
        if (index !== -1) {
          this.tempSelection.splice(index, 1)
        }
      }
      // console.log('所有已选中', this.tempSelection);
      // 判断选中还是取消选中
      if (selection.length && selection.some((item) => item === row)) {
        // 选中时
        // 判断 新增的指标与已有的指标是否在同一个指标体系下
        selection.forEach((item) => {
          if (
            // item.indicatorSystemId === row.indicatorSystemId &&
            // item.pkid !== row.pkid
            item.quotaName === row.quotaName &&
            item.pkid !== row.pkid
          ) {
            // 去除选中重复的行
            setTimeout(() => {
              this.$refs.tableRef.toggleRowSelection(item, false)
            }, 100)
          }
        })
      }
    },
    filterIndex(val) {
      this.$emit('update:page', { ...this.page, quotaName: val })
    },
    filterTable(val) {
      this.$emit('update:page', { ...this.page, name: val })
    },
    filterHandler(value, row, column) {
      // console.log(value, row, column);
      const property = column['property']
      return row[property] === value
    },
    handleSizeChange(pageSize) {
      this.$emit('update:page', { ...this.page, pageSize, pageIndex: 1 })
    },
    handleCurrentChange(val) {
      this.$emit('update:page', { ...this.page, pageIndex: val })
    },
    // flag = null
    fetchData() {
      getAreaList().then((res) => {
        if (res.success) {
          this.cityOptions = res.data.map((item) => {
            return {
              value: item.pkid,
              label: item.areaName,
            }
          })
          // if (flag && this.cityOptions.length) {
          //   this.page.areaId = this.cityOptions[0].value;
          //   getYearList(this.page.areaId).then(res => {
          //     if (res.success) {
          //       const data = [...res.data];
          //       data.sort();
          //       this.yearOptions = data
          //         .map(item => {
          //           return {
          //             value: item,
          //             label: item + '年',
          //           };
          //         })
          //         .reverse();
          //       if (flag && this.yearOptions.length) {
          //         this.page.year = this.yearOptions[0].value;
          //       }
          //       this.yearOptionsLoading = false;
          //     }
          //   });
          // }
          this.cityOptionsLoading = false
        }
      })
    },
    handleCityChange() {
      this.page.year = ''
      this.page.dimensionId = ''
      this.page.name = ''
      this.page.quotaName = ''
      this.$emit('update:page', { ...this.page, pageIndex: 1, total: 0 })
      getYearList(this.page.areaId).then((res) => {
        if (res.success) {
          const data = [...res.data]
          data.sort()
          this.yearOptions = data
            .map((item) => {
              return {
                value: item,
                label: item + '年',
              }
            })
            .reverse()
          this.yearOptionsLoading = false
        }
      })
    },
    handleYearChange() {
      // console.log(this.query.year);
      this.page.dimensionId = ''
      this.page.name = ''
      this.page.quotaName = ''
      this.$emit('update:page', { ...this.page, pageIndex: 1, total: 0 })
      getAreaList(this.page.year).then((res) => {
        if (res.success) {
          this.cityOptions = res.data.map((item) => {
            return {
              value: item.pkid,
              label: item.areaName,
            }
          })
          this.cityOptionsLoading = false
        }
      })
    },
    handleDimensionChange() {
      this.$emit('update:page', {
        ...this.page,
        pageIndex: 1,
        total: 0,
        name: '',
        quotaName: '',
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.el-input {
  width: 50%;
  margin-bottom: 1rem;
}

.cus-header-row {
  display: none;
  &:first-child {
    display: none;
  }
}

.index-definition {
  width: 15rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

.top {
  display: flex;
}

.footer {
  padding: 10px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.top-item {
  margin-right: 20px;

  &-sel {
    margin-right: 20px;
    width: 400px;
  }
}
</style>
